package com.ejlchina.tool.util

import android.os.Handler
import android.os.Looper
import java.util.concurrent.CountDownLatch

object Executor {

    private var io: Handler? = null
    private val main: Handler = Handler(Looper.getMainLooper())

    private val latch = CountDownLatch(1)

    init {
        val thread = Thread {
            Looper.prepare()
            io = Handler()
            latch.countDown()
            Looper.loop()
        }
        thread.isDaemon = true
        thread.start()
    }

    val mainHandler: Handler
        get() = main

    val ioHandler: Handler
        get() {
            if (io == null) {
                latch.await()
            }
            return io!!
        }

    fun runOnMain(run: Runnable) {
        main.post(run)
    }

    fun delayOnMain(run: Runnable, delayMills: Long) {
        main.postDelayed(run, delayMills)
    }

    fun repeatOnMain(run: () -> Boolean, intervalMills: Long, immediately: Boolean = true) {
        repeat(main, run, intervalMills, immediately)
    }

    fun runOnIO(run: Runnable) {
        ioHandler.post(run)
    }

    fun delayOnIO(run: Runnable, delayMills: Long) {
        ioHandler.postDelayed(run, delayMills)
    }

    fun repeatOnIO(run: () -> Boolean, intervalMills: Long, immediately: Boolean = true) {
        repeat(ioHandler, run, intervalMills, immediately)
    }

    fun repeat(handler: Handler, run: () -> Boolean, intervalMills: Long, immediately: Boolean = true) {
        if (immediately) {
            if (run()) {
                handler.postDelayed({
                    repeat(handler, run, intervalMills, immediately)
                }, intervalMills)
            }
        } else {
            handler.postDelayed({
                if (run()) {
                    repeat(handler, run, intervalMills, immediately)
                }
            }, intervalMills)
        }
    }

}
